package com.buobao.controller;

import com.buobao.entity.Evaluation;
import com.buobao.service.EvaluationService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/evaluation")
public class EvaluationController {
    @Resource
    private EvaluationService evaluationService;

    @GetMapping("/list/{bookId}")
    @ResponseBody
    public List<Evaluation> getEvaluationList(@PathVariable("bookId") Long bookId)
    {
        List<Evaluation> evaluationList = evaluationService.getEvaluationByBookId(bookId);
        return evaluationList;
    }


    @PostMapping("/add")
    @ResponseBody
    public Map addEvaluation(Long memberId, Long bookId, Integer score, String content) {
        Map result = new HashMap();
        Evaluation evaluation = new Evaluation();
        evaluation.setCreateTime(new Date());
        evaluation.setBookId(bookId);
        evaluation.setContent(content);
        evaluation.setMemberId(memberId);
        evaluation.setScore(score);
        evaluationService.insertEvaluation(evaluation);
        result.put("evaluationId", evaluation.getEvaluationId());
        result.put("code","0");
        return result;
    }


    @PostMapping("/favit")
    @ResponseBody
    public Map favit(Long evaluationId, HttpServletRequest request) {
        Evaluation evaluation = evaluationService.getEvaluationById(evaluationId);
        HttpSession session = request.getSession();
        Set<Long> favitlist = (Set<Long>) session.getAttribute("favit_list");
        if (favitlist==null) {
            favitlist = new HashSet<>();
            favitlist.add(evaluationId);
            evaluation.setEnjoy(evaluation.getEnjoy()+1);
        } else {
            if (favitlist.contains(evaluationId)) {
                favitlist.remove(evaluationId);
                evaluation.setEnjoy(evaluation.getEnjoy()-1);
            } else {
                favitlist.add(evaluationId);
                evaluation.setEnjoy(evaluation.getEnjoy()+1);
            }
        }
        session.setAttribute("favit_list", favitlist);
        evaluationService.updateEvaluation(evaluation);
        Map result = new HashMap();
        result.put("code", "0");
        result.put("enjoy", evaluation.getEnjoy());
        return result;
    }
}



























